package com.ndp.fb.fbagent.service.impl;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.dubbo.config.annotation.Service;
import com.ndp.fb.constant.CommonConstants;
import com.ndp.fb.fbagent.service.OauthFbService;
import com.ndp.fb.model.fbagent.param.APIPriority;
import com.ndp.fb.model.fbagent.param.IdParam;
import com.ndp.fb.model.fbagent.param.businesses.BusinessesParam;
import com.ndp.fb.model.fbagent.param.businesses.UserpermissionsParam;
import com.ndp.fb.model.fbagent.param.connectionobjects.FBConnectionObjectsParam;
import com.ndp.fb.model.fbagent.param.entrustaccount.EntrustAccountParam;
import com.ndp.fb.model.fbagent.param.oauth.CheckTokenParam;
import com.ndp.fb.model.fbagent.param.oauth.OauthParam;
import com.ndp.fb.model.fbagent.result.FacebookResult;
import com.ndp.fb.model.fbagent.result.businesses.FBBusinesses;
import com.ndp.fb.model.fbagent.result.businesses.FBMe;
import com.ndp.fb.model.fbagent.result.businesses.UserpermissionsResult;
import com.ndp.fb.model.fbagent.result.connectionobjects.FBConnectionObjects;
import com.ndp.fb.model.fbagent.result.entrustaccount.EntrustAccounts;
import com.ndp.fb.model.fbagent.result.entrustaccount.TokenResult;
import com.restfb.DefaultJsonMapper;
import com.restfb.JsonMapper;
import com.restfb.Parameter;
import com.restfb.json.JsonObject;

/**
 * Created by elvis on 2015/3/24.
 */
@Service
public class OauthFbServiceImpl extends AbstractFBagentService implements OauthFbService {

    private Logger logger = LoggerFactory.getLogger(AdSetFBServiceImpl.class);

    @Override
    public FBMe getFbMe(String accessToken) {
        BusinessesParam prams = new BusinessesParam();
        prams.setAccessToken(accessToken);
        prams.setApiPriorityCode(APIPriority.GetFBMe.getCode());
        prams.setFields("id,email,first_name,gender,last_name,locale,name,timezone,updated_time,is_verified");
        Parameter[] parameterList = adapterArray(prams);
        String uri = "/me";
        return syncFetchObjectResult(uri, accessToken, FBMe.class, parameterList);
    }


    @Override
    public List<UserpermissionsResult> getUserpermissionsResult(String accessToken, Long fbBusinessesId, int offset, int limit, boolean isAll) {
        UserpermissionsParam params = new UserpermissionsParam();
        params.setAccessToken(accessToken);
        params.setApiPriorityCode(APIPriority.GetUserpermissions.getCode());
        params.setFields("adaccount_permissions,email,role,status,business_persona,page_permissions");
        List<Parameter> parameterList = adapter(params);
        String uri = "/" + fbBusinessesId + "/userpermissions";
        logger.info("url:" + uri);
        FacebookResult<UserpermissionsResult> result = syncFetchFacebookResult(uri, accessToken, parameterList, isAll,
                offset, limit, UserpermissionsResult.class);
        return result.getObjects();
    }

    @Override
    public String getAccessToken(String appId,String appSecret,String code, String redirectUri, String locale) {
        OauthParam param = new OauthParam(locale, appId, appSecret, code, redirectUri);
        param.setApiPriorityCode(APIPriority.GetAccessToken.getCode());
        Parameter[] parameters = adapterArray(param);
        String uri = "/oauth/access_token";
        return getAccessToken(uri, parameters).getAccessToken();
    }

    @Override
    public void getFBConnectionObjects(FBConnectionObjectsParam requestParam,Map<String, String> equipmentMap) {
//        FBConnectionObjectsParam params = new FBConnectionObjectsParam();
//        params.setApiPriorityCode(APIPriority.FetchConnectionobjects.getCode());
//        List<Parameter> parameterList = adapter(params);
//        String uri = "/act_" + fbAccountId + "/connectionobjects";
//        FacebookResult<FBConnectionObjects> result = syncFetchFacebookResult(uri, accessToken, parameterList, true,
//                0, CommonConstants.NUM_INT_500, FBConnectionObjects.class);
//        return result.getObjects();
        
        if(StringUtils.isNotEmpty(equipmentMap.get("after"))){
        	requestParam.setAfter(equipmentMap.get("after"));
        }
        Parameter[] parameters = this.adapterArray(requestParam);
        String uri = "/act_" + requestParam.getFbAccountId() + "/connectionobjects";
        makeGetRequest(uri, requestParam.getAccessToken(), parameters);
    }
    @Override
    public List<FBConnectionObjects> getFBConnectionObjects(Long fbAccountId, String accessToken) {
        FBConnectionObjectsParam params = new FBConnectionObjectsParam();
        params.setApiPriorityCode(APIPriority.FetchConnectionobjects.getCode());
        List<Parameter> parameterList = adapter(params);
        String uri = "/act_" + fbAccountId + "/connectionobjects";
        FacebookResult<FBConnectionObjects> result = syncFetchFacebookResult(uri, accessToken, parameterList, true, 0, CommonConstants.NUM_INT_500, FBConnectionObjects.class);
        return result.getObjects();
    }
    @Override
    public List<FBBusinesses> getFbBusinessesList(String accessToken) {
        BusinessesParam prams = new BusinessesParam();
        prams.setApiPriorityCode(APIPriority.FetchConnectionobjects.getCode());
        prams.setAccessToken(accessToken);
        List<Parameter> parameterList = adapter(prams);
        String uri = "/me/businesses";
        FacebookResult<FBBusinesses> result = syncFetchFacebookResult(uri, accessToken, parameterList, true,
                0, CommonConstants.NUM_INT_500, FBBusinesses.class);
        return result.getObjects();
    }


    /**
     * @param accessToken
     * @param offset
     * @param limit
     * @param isAll
     * @return
     * @discription
     * @author giser.yang
     * 创建时间 2015年6月5日 下午1:03:14
     * @see com.ndp.fb.fbagent.service.OauthFbService#getEntrustAccountsByFbUser(java.lang.String, int, int, boolean)
     */

    @Override
    public List<EntrustAccounts> getEntrustAccountsByFbUser(String accessToken,
                                                            int offset, int limit, boolean isAll) {
        EntrustAccountParam params = new EntrustAccountParam();
        params.setAccessToken(accessToken);
        params.setApiPriorityCode(APIPriority.GetEntrustAccounts.getCode());
        params.setFields("account_id,access_status,access_type,balance,name,account_status,timezone_name,timezone_id,tos_accepted");
        List<Parameter> parameterList = adapter(params);
        String uri = "/me/adaccounts";
        FacebookResult<EntrustAccounts> result = syncFetchFacebookResult(uri, accessToken, parameterList, isAll,
                offset, limit, EntrustAccounts.class);
        return result.getObjects();
    }


    /**
     * 检查 accessToken 是否失效
     *
     * @param accessToken app 应用的token,与系统中其他使用的不同
     * @param inputToken  需要检查的 token,即每次请求发送需要使用的token
     * @return
     */
    @Override
    public TokenResult checkToken(String accessToken, String inputToken) {
        String uri = "/debug_token";
        CheckTokenParam params = new CheckTokenParam(inputToken);
        Parameter[] parameterList = this.adapterArray(params);
        String json = syncFetchObjectResult(uri, accessToken, String.class, parameterList);
        JsonObject jsonObject = new JsonObject(json);
        JsonMapper jsonMapper = new DefaultJsonMapper();
        TokenResult tokenResult = jsonMapper.toJavaObject(jsonObject.getString("data"), TokenResult.class);
        return tokenResult;
    }

    /**
     * 删除fb对象
     */
    @Override
    public void deleteObject(IdParam param)
    {
        param.setApiPriorityCode(APIPriority.DeleteOjbect.getCode());
        List<Parameter> params = adapter(param);
        String uri = "/" + param.getId();
        deleteObject(uri, param.getAccessToken(), params.toArray(new Parameter[]{}));
    }

}
